package 实验六;

/**
 * 命令接口
 */
interface Command {
    void execute();
    void undo();
}

/**
 * 具体的业务逻辑
 */
class Light {
    public void on() {
        System.out.println("灯已打开");
    }

    public void off() {
        System.out.println("灯已关闭");
    }
}

/**
 *  创建具体命令类
 */
class LightOnCommand implements Command {
    private Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.on();
    }

    @Override
    public void undo() {
        light.off();
    }
}

class LightOffCommand implements Command {
    private Light light;

    public LightOffCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.off();
    }

    @Override
    public void undo() {
        light.on();
    }
}

/**
 * 创建调用者
 */
class RemoteControl {
    private Command onCommand;
    private Command offCommand;
    private Command undoCommand;

    public RemoteControl(Command onCommand, Command offCommand) {
        this.onCommand = onCommand;
        this.offCommand = offCommand;
        this.undoCommand = null; // 初始状态下没有可撤销的操作
    }

    public void setUndoCommand(Command command) {
        this.undoCommand = command;
    }

    public void pressOnButton() {
        onCommand.execute();
        setUndoCommand(onCommand);
    }

    public void pressOffButton() {
        offCommand.execute();
        setUndoCommand(offCommand);
    }

    public void pressUndoButton() {
        if (undoCommand != null) {
            undoCommand.undo();
        } else {
            System.out.println("没有可撤销的操作");
        }
    }
}

public class 命令模式 {
    public static void main(String[] args) {
        // 创建接收者
        Light light = new Light();

        // 创建命令
        Command lightOn = new LightOnCommand(light);
        Command lightOff = new LightOffCommand(light);

        // 创建调用者并关联命令
        RemoteControl remote = new RemoteControl(lightOn, lightOff);

        // 模拟用户按下按钮
        remote.pressOnButton(); // 输出: 灯已打开
        remote.pressOffButton(); // 输出: 灯已关闭
        remote.pressUndoButton(); // 输出: 灯已打开 (撤销关灯操作)
        remote.pressUndoButton(); // 输出: 灯已关闭 (撤销开灯操作)
    }
}
